#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版DMG创建工具 - 专注于背景图集成
"""

import os
import sys
import json
import shutil
import subprocess
import tempfile
from pathlib import Path
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def create_dmg_with_background(app_path, version="2.7.2", output_dir="dist"):
    """创建带背景图的DMG"""

    logger.info(f"开始创建带背景图的DMG: {app_path}")

    # 检查输入
    app_path = Path(app_path)
    if not app_path.exists():
        logger.error(f"应用不存在: {app_path}")
        return False

    output_dir = Path(output_dir)
    output_dir.mkdir(exist_ok=True)

    # 创建临时目录
    with tempfile.TemporaryDirectory(prefix='dmg_simple_') as temp_dir:
        temp_path = Path(temp_dir)
        content_dir = temp_path / 'dmg_content'
        content_dir.mkdir()

        logger.info(f"临时目录: {content_dir}")

        # 1. 复制应用
        app_dest = content_dir / app_path.name
        shutil.copytree(app_path, app_dest)
        logger.info("✅ 复制应用程序")

        # 2. 创建Applications链接
        apps_link = content_dir / 'Applications'
        apps_link.symlink_to('/Applications')
        logger.info("✅ 创建Applications链接")

        # 3. 复制背景图
        background_dir = content_dir / '.background'
        background_dir.mkdir()

        background_src = Path('resources/dmg_background.png')
        if background_src.exists():
            background_dest = background_dir / 'background.png'
            shutil.copy2(background_src, background_dest)
            logger.info("✅ 复制背景图")
        else:
            logger.warning("⚠️ 背景图不存在，使用默认样式")

        # 4. 创建DMG
        dmg_name = f"LimeReader_v{version}_macOS.dmg"
        dmg_path = output_dir / dmg_name

        # 删除已存在的DMG
        if dmg_path.exists():
            dmg_path.unlink()

        logger.info("创建DMG文件...")
        cmd = [
            'hdiutil', 'create',
            '-srcfolder', str(content_dir),
            '-volname', f'LimeReader {version}',
            '-fs', 'HFS+',
            '-format', 'UDZO',
            '-imagekey', 'zlib-level=9',
            str(dmg_path)
        ]

        result = subprocess.run(cmd, capture_output=True, text=True)

        if result.returncode == 0:
            logger.info(f"✅ DMG创建成功: {dmg_path}")
            logger.info(f"文件大小: {dmg_path.stat().st_size / (1024*1024):.1f} MB")
            return True
        else:
            logger.error(f"❌ DMG创建失败: {result.stderr}")
            return False

if __name__ == "__main__":
    success = create_dmg_with_background("dist/LimeReader.app")
    sys.exit(0 if success else 1)